package com.shaoshaohuo.app.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.entity.AddNewAddressEntity;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.CountyidEntity;
import com.shaoshaohuo.app.entity.ProvinceEntity;
import com.shaoshaohuo.app.entity.post.CityEntity;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.utils.ToastUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 新增地址界面
 * Created by Administrator on 2017/6/11.
 */

public class NewaddAdders extends BaseActivity implements OptionsPickerView.OnOptionsSelectListener, View.OnClickListener {

    private OptionsPickerView pvNoLinkOptions;
    private List<ProvinceEntity.DataBean> data;
    private int shj = 0;
    private List<CityEntity.DataBean> data1;
    private String provinceid = "";
    private List<CountyidEntity.DataBean> data3;

    private String city = "";
    private String Province = "";
    private String county = "";
    private Handler handler = new Handler();
    private LinearLayout newaddadders_lin_city;
    private TextView newaddadders_tv_city;
    private TextView textView2;
    private ImageView newaddadders_iv_deflute;
    private RadioGroup rag_type;
    private String latitude;
    private String longitude;
    private EditText newaddadders_edt_name;
    private EditText newaddadders_edt_phonenum;
    private EditText newaddadders_edt_xxaddress;
    private String id;
    private TextView toolbar_topname;
    private String addressid;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_addnewadderss);

        /**
         * 看看是修改頁面还是新增
         */
        initview();
        chage();


        changeTransltestaus(((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0), this, TransltestausModel.NoePicter, getResources().getColor(R.color.color_49b152));
        View viewById = findViewById(R.id.imageview_topbar_left_backImage);
        viewById.setVisibility(View.VISIBLE);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        findViewById(R.id.imageview_message).setVisibility(View.GONE);
        pvNoLinkOptions = new OptionsPickerView.Builder(this, this).build();
//        pvNoLinkOptions.setNPicker(objects,);
        ShopHttpConfig.App_addressgetarea(this, "", "", new Okhttputils.OkutListener()

        {
            @Override
            public void error(Call call, IOException e) {

            }

            @Override
            public void error(Call call, int code) {

            }

            @Override
            public void suseff(Call call, Response response, Object o) {
                ProvinceEntity provinceEntity = (ProvinceEntity) o;
                data = provinceEntity.getData();
                ArrayList<String> strings = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    strings.add(data.get(i).getProvince());
                }
                pvNoLinkOptions.setPicker(strings);
            }
        }, ProvinceEntity.class);


    }


    /**
     * 初始化view
     */
    private void initview() {
        toolbar_topname = (TextView) findViewById(R.id.toolbar_topname);
        toolbar_topname.setText("新增地址");
        textView2 = (TextView) findViewById(R.id.textView2);
        newaddadders_iv_deflute = (ImageView) findViewById(R.id.Newaddadders_iv_deflute);
        newaddadders_iv_deflute.setOnClickListener(this);
        rag_type = (RadioGroup) findViewById(R.id.rag_type);
        newaddadders_edt_name = (EditText) findViewById(R.id.Newaddadders_edt_name);
        newaddadders_edt_phonenum = (EditText) findViewById(R.id.newaddadders_edt_phonenum);
        newaddadders_edt_xxaddress = (EditText) findViewById(R.id.newaddadders_edt_xxaddress);
        newaddadders_lin_city = (LinearLayout) findViewById(R.id.Newaddadders_lin_city);
        newaddadders_lin_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(NewaddAdders.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                        shj = 0;
                if (data.size() > 0) {
                    ArrayList<String> strings = new ArrayList<>();
                    for (int i = 0; i < data.size(); i++) {
                        strings.add(data.get(i).getProvince());
                    }
                    pvNoLinkOptions.setPicker(strings);
                }
                pvNoLinkOptions.show();
            }
        });
        newaddadders_tv_city = (TextView) findViewById(R.id.Newaddadders_tv_city);
        LinearLayout Newaddadders_lin_adderss = (LinearLayout) findViewById(R.id.Newaddadders_lin_adderss);
        Newaddadders_lin_adderss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(v.getContext(), AdderssPOIActivity.class);
                intent.putExtra("city", newaddadders_tv_city.getText().toString().trim());
                //requsecode 1
//                newaddadders_tv_city/
                startActivityForResult(intent, 1);
            }
        });
    }

    /**
     * 三级列表
     *
     * @param options1
     * @param options2
     * @param options3
     * @param v
     */
    @Override
    public void onOptionsSelect(int options1, int options2, int options3, View v) {
        if (shj == 0) {
            //第一次点击。请求开放市
            ProvinceEntity.DataBean dataBean = data.get(options1);
            provinceid = dataBean.getProvinceid();
            Province = dataBean.getProvince();
            ShopHttpConfig.App_addressgetarea(NewaddAdders.this, provinceid, "", new Okhttputils.OkutListener() {
                @Override
                public void error(Call call, IOException e) {

                }

                @Override
                public void error(Call call, int code) {

                }

                @Override
                public void suseff(Call call, Response response, Object o) {
                    CityEntity cityEntity = (CityEntity) o;
                    data1 = cityEntity.getData();
                    final ArrayList<String> strings = new ArrayList<>();
                    for (int i = 0; i < data1.size(); i++) {
                        strings.add(data1.get(i).getCity());
                    }
                    shj += 1;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            pvNoLinkOptions = new OptionsPickerView.Builder(NewaddAdders.this, NewaddAdders.this).build();
                            pvNoLinkOptions.setPicker(strings);
                            pvNoLinkOptions.show();
                        }
                    });


                }
            }, CityEntity.class);
        }
        if (shj == 1) {

            CityEntity.DataBean dataBean = data1.get(options1);
            String cityid = dataBean.getCityid();
            city = dataBean.getCity();

            ShopHttpConfig.App_addressgetarea(NewaddAdders.this, provinceid, cityid, new Okhttputils.OkutListener() {
                @Override
                public void error(Call call, IOException e) {

                }

                @Override
                public void error(Call call, int code) {

                }

                @Override
                public void suseff(Call call, Response response, Object o) {
                    CountyidEntity countyidEntity = (CountyidEntity) o;
                    data3 = countyidEntity.getData();
                    final ArrayList<String> strings = new ArrayList<>();
                    for (int i = 0; i < data3.size(); i++) {
                        strings.add(data3.get(i).getCounty());
                    }
//                    pvNoLinkOptions.setPicker(strings);
                    shj += 1;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            pvNoLinkOptions = new OptionsPickerView.Builder(NewaddAdders.this, NewaddAdders.this).build();
                            pvNoLinkOptions.setPicker(strings);
                            pvNoLinkOptions.show();
                        }
                    });
                }
            }, CountyidEntity.class);
        } else if (shj == 2) {
            shj = 0;
            if (data3 != null && data3.size() > options1) {
                CountyidEntity.DataBean dataBean = data3.get(options1);
                county = dataBean.getCounty();
                id = dataBean.getId();

                newaddadders_tv_city.setText(Province + city + county);
            } else {
                ToastUtil.toast("请选择完整的省市");
            }


        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 2) {
            AddNewAddressEntity address = (AddNewAddressEntity) data.getSerializableExtra("address");
            String addressname = address.getAddressname();

            latitude = address.getLatitude();
            longitude = address.getLongitude();
            textView2.setText(addressname);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.Newaddadders_iv_deflute:
                v.setSelected(!v.isSelected());
                break;
        }
    }

    /**
     * 保存地址的按鈕点击
     *
     * @param view
     */
    public void preservation(View view) {
        String trim = newaddadders_edt_name.getText().toString().trim();
        String phonenum = newaddadders_edt_phonenum.getText().toString().trim();
        String xxaddress = newaddadders_edt_xxaddress.getText().toString().trim();
        String tv_city = newaddadders_tv_city.getText().toString().trim();
        String textView = textView2.getText().toString().trim();
        if (TextUtils.isEmpty(trim) && TextUtils.isEmpty(phonenum) && TextUtils.isEmpty(xxaddress) && TextUtils.isEmpty(tv_city) && TextUtils.isEmpty(textView)) {
            ToastUtil.toast("请填写完整信息");
            return;
        } else {
            textView = textView.replace(tv_city, "");
            /**
             *     name：（收货人姓名）trim
             phone：（收货人姓名）phonenum
             areaid：（地区id） 详情查看返回区的id 字段 id
             details:（详细地址）例如：黄河中路汇智广场52号 textView2
             adressnum（楼号门牌号）xxaddress
             longitude：(经度) latitude
             latitude：（纬度） longitude
             default（是否为默认地址）1.默认地址 0普通地址   newaddadders_iv_deflute.isseleter
             type：（地址类型）1. 住宅 2.公司 3.学校 4.其他 rag
             */
            boolean selected = newaddadders_iv_deflute.isSelected();
            int type = 0;
            for (int i = 0; i < rag_type.getChildCount(); i++) {
                RadioButton childAt = (RadioButton) rag_type.getChildAt(i);
                boolean checked = childAt.isChecked();
                if (checked) {
                    type = i;
                    break;
                }
            }
            String defaulta = "2";
            if (selected) {
                //moren
                defaulta = "1";
            } else {
                defaulta = "2";
            }
            Log.e("TAG", "preservation: " + "name" + trim + "phonenum" + phonenum + "id" + id + "details" + textView + "adressnum" + xxaddress + "longitude" + longitude + "latitude" + latitude + "defaulta" + defaulta + "type" + type + "addressid===" + addressid);
            if (addressid == null) {

                ShopHttpConfig.App_addressadds(this, trim, phonenum, id, textView, xxaddress, longitude, latitude, defaulta, (type + 1) + "", new Okhttputils.OkutListener() {
                    @Override
                    public void error(Call call, IOException e) {

                    }

                    @Override
                    public void error(Call call, int code) {

                    }

                    @Override
                    public void suseff(Call call, Response response, Object o) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.toast("保存成功");
                                finish();
                            }
                        });
                    }
                }, BaseEntity.class);

            } else {
                ShopHttpConfig.App_addressupdate(this, trim, phonenum, id, textView, xxaddress, longitude, latitude, defaulta, addressid, (type + 1) + "", new Okhttputils.OkutListener() {
                    @Override
                    public void error(Call call, IOException e) {

                    }

                    @Override
                    public void error(Call call, int code) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.toast("修改失败");
                                finish();
                            }
                        });
                    }

                    @Override
                    public void suseff(Call call, Response response, Object o) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.toast("修改成功");
                                finish();
                            }
                        });
                    }
                }, BaseEntity.class);
            }
        }
    }

    private void chage() {
        Intent intent = getIntent();
        String chage = intent.getStringExtra("chage");
        String name = intent.getStringExtra("name");
        String phone = intent.getStringExtra("phone");
        String city = intent.getStringExtra("city");
        String areaid = intent.getStringExtra("areaid");
        addressid = intent.getStringExtra("addressid");
        String details = intent.getStringExtra("details");
        String adressnum = intent.getStringExtra("adressnum");
        longitude = intent.getStringExtra("longitude");
        latitude = intent.getStringExtra("latitude");
        String aDefault = intent.getStringExtra("default");
        String type = intent.getStringExtra("type");
        //头部变为修改
        if (chage != null && chage.equals("修改")) {
            toolbar_topname.setText("修改地址");
            /**
             * id
             */
            /**
             *     name：（收货人姓名）trim
             phone：（收货人姓名）phonenum
             areaid：（地区id） 详情查看返回区的id 字段 id
             details:（详细地址）例如：黄河中路汇智广场52号 textView2
             adressnum（楼号门牌号）xxaddress
             longitude：(经度) latitude
             latitude：（纬度） longitude
             default（是否为默认地址）1.默认地址 0普通地址   newaddadders_iv_deflute.isseleter
             type：（地址类型）1. 住宅 2.公司 3.学校 4.其他 rag
             */
            id = areaid;

            newaddadders_tv_city.setText(city);
            newaddadders_edt_name.setText(name);
            newaddadders_edt_phonenum.setText(phone);
            newaddadders_edt_xxaddress.setText(adressnum);
            textView2.setText(details);
            if (aDefault.equals("1")) {
                newaddadders_iv_deflute.setSelected(true);
            } else {
                newaddadders_iv_deflute.setSelected(false);
            }
            Integer integer = Integer.valueOf(type);
            Log.e("TAG", "chage: " + type);
            RadioButton childAt = (RadioButton) rag_type.getChildAt(integer - 1);
            if(childAt!=null){
                childAt.setChecked(true);
            }

        }

    }
}


